#!/usr/bin/env python3
import sys
import math
import os, time, random
import json
from multiprocessing import Pool

def concat_picture(src_task_file, processed_results_dir, sub_iter, sub_type, symbol):
    print("=============== Concat file =============")

    fp = open(src_task_file, "r")

    sub_list = []
    for line in fp.readlines():
        subj_name = line.replace("\n", "")
        subj_name = subj_name.strip()

        sub_list.append(subj_name)

    sub_chunk_list = [sub_list[i:i+5] for i in range(0,len(sub_list),5)]

    full_list = []

    chunk_index = 0
    for chunk_item in sub_chunk_list:
        conv_cmd = 'convert'

        for sub_item in chunk_item:
            subj_name = line.replace("\n", "")
            subj_name = subj_name.strip()

            sud_dir = os.path.join(processed_results_dir, subj_name)
            iter_sub = os.path.join(sud_dir, sub_iter)

            tarfile = 'fsaverage4_if_lh_med.tif'
            full_tar_file = os.path.join(iter_sub, tarfile)
            tar_pre_file = 'wp_fsaverage4_if_lh_med.tif'
            full_tar_pre_file = os.path.join(iter_sub, tarfile)

            cp_cmd = 'cp {} {}'.format(full_tar_file, full_tar_pre_file)
            print('[CMD]: %s' % cp_cmd)
            os.system(cp_cmd)

            conv_press = 'convert {} -gravity southeast -fill white -pointsize 32 -draw "text 5,5 {}" {}'.format(full_tar_pre_file, subj_name, full_tar_pre_file)
            print('[CMD]: %s' % conv_press)
            os.system(conv_press)

            conv_cmd += ' ' + full_tar_pre_file

        des_file = str(chunk_index) + '_' + sub_type + '_' + symbol + '_' + sub_iter + '.png'
        full_des_file = os.path.join(processed_results_dir, des_file)
        conv_cmd += ' -gravity north +append ' + full_des_file

        print('[CMD]: %s' % conv_cmd)
        os.system(conv_cmd)

        full_list.append(full_des_file)

        chunk_index += 1

    conv_cmd = 'convert'
    for full_item in full_list:
        conv_cmd += ' ' + full_item

    des_final_file = sub_type + '_' + symbol + '_' + sub_iter + '.png'
    full_des_final_file = os.path.join(processed_results_dir, des_final_file)
    conv_cmd += ' -gravity east -append ' + full_des_final_file

    print('[CMD]: %s' % conv_cmd)
    os.system(conv_cmd)

    print("================== Done ==================")

if __name__=='__main__':
    project_dir = '/home/liang/Projects/ASD_QC'
    symbol      = "OHSU"
    sub_type    = "ASD"
    list_file   = 'censored_sub_list_' + sub_type + '_' + symbol + '.txt'

    list_dir = os.path.join(project_dir, 'Lists')
    src_task_file = os.path.join(list_dir, list_file)
    processed_results_dir = os.path.join(project_dir, 'Results/Screencaps')

    iter_name = 'Iter_10'
    concat_picture(src_task_file, processed_results_dir, iter_name, sub_type, symbol)
